//
//  OtherComplementedTableViewController.swift
//  甜言蜜语
//
//  Created by 王剑伟 on 16/7/6.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import ActionSheetPicker_3_0
import SVProgressHUD
class OtherComplementedTableViewController: UITableViewController,ActionSheetCustomPickerDelegate {
   
    var phone: String!
    var passWord: String!
    var registType: String!
    var identyCode: String?
    
    var memberType: String!
    var sex: String!
    var modelList: loginInfo?{
        didSet{
            
        }
    }
    var msg: regiestInfo?
    var img: UIImage?
    @IBOutlet weak var manBtn: UIButton!
    @IBOutlet weak var femaleBtn: UIButton!
    @IBOutlet weak var brithday: UILabel!
    @IBOutlet weak var beithdayPlace: UILabel!
    @IBOutlet weak var company: UITextField!
    @IBOutlet weak var workared: UILabel!
    @IBOutlet weak var workaredPlace: UILabel!
    @IBOutlet weak var address: UITextField!
    @IBOutlet weak var workTime: UILabel!
    @IBOutlet weak var workTimePlace: UILabel!
    @IBOutlet weak var nickName: UITextField!
    
    
    var index1: NSInteger = 0 // 省下标
    var index2: NSInteger = 0 // 市下标
    var index3: NSInteger = 0 // 区下标
    
    var provinceArr: NSArray! //省
    var countryArr: NSArray! // 市
    var districtArr: NSArray! // 区
    var addressArr: NSArray! // 解析出来的最外层的数组
    var typeStr: String!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        publicMethod.setHUDStyle()
           self.img = UIImage(named: "placeholder")
           self.title = "信息补全"
        self.calculateFirstData()
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    func calculateFirstData(){
        
        loadFirstData()
        let cityNameArr = NSMutableArray()
        
        print(addressArr.count)
        for cityName in (addressArr[index1].allValues.first) as! NSArray {
            
            let name1 = (cityName as! NSDictionary).allKeys.first
            cityNameArr.addObject(name1!)
        }
        // 组装对应省下面的市
        countryArr = cityNameArr
        
        districtArr = addressArr[index1].allObjects[0][index2].allValues[0] as! NSArray
        //self.districtArr = [[self.addressArr[self.index1] allValues][0][self.index2] allValues][0];
    }
    func loadFirstData(){
        
        let path = NSBundle.mainBundle().pathForResource("address", ofType: "json")
        print(path)
        
        let data = NSData.init(contentsOfFile: path!)
        
        guard let myArr = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) else {
            
            return
        }
        
        addressArr = myArr as! NSArray
        
        let firstName = NSMutableArray()
        for dict in addressArr {
            
            let name = (dict as! NSDictionary).allKeys.first
            firstName.addObject(name!)
        }
        provinceArr = firstName
        
        
    }
    //MARK: UIPickerViewDataSource Implementation
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 2
    }
    func pickerView(_pickerView: UIPickerView,
                    numberOfRowsInComponent component: Int) -> Int{
        switch (component)
        {
        case 0: return self.provinceArr.count;
        case 1: return self.countryArr.count;
        
        default:break;
        }
        return 0;
    }
    
    func pickerView(pickerView: UIPickerView,
                    titleForRow row: Int,
                                forComponent component: Int) -> String?{
        
        switch (component)
        {
        case 0: return self.provinceArr[row] as? String
        case 1: return self.countryArr[row] as? String
        
        default:break;
        }
        return nil;
    }
    func pickerView(pickerView: UIPickerView,
                    viewForRow row: Int,
                               forComponent component: Int,
                                            reusing view: UIView?) -> UIView{
        
        
        let label: UILabel! = UILabel()
        label!.font = UIFont.systemFontOfSize(14)
        
        var title = ""
        switch component {
        case 0:
            title = self.provinceArr[row] as! String
        case 1:
            title = self.countryArr[row] as! String
        
        default:
            break
        }
        
        label!.textAlignment = NSTextAlignment.Center
        label!.text = title
        return label!
        
    }
    func pickerView(pickerView: UIPickerView,
                    didSelectRow row: Int,
                                 inComponent component: Int){
        switch component {
        case 0:
            self.index1 = row
            self.index2 = 0
           
           
            // 滚动的时候都要进行一次数组的刷新
            self.calculateFirstData()
            pickerView.reloadComponent(1)
           
            pickerView.selectRow(0, inComponent: 1, animated: true)
            
            
        case 1:
            self.index2 = row
        default:
            break
        }
        
    }
    //MARK:点击完成的按钮时执行
    func actionSheetPickerDidSucceed(actionSheetPicker: AbstractActionSheetPicker!, origin: AnyObject!) {
        var detailAddress = String()
        if self.index1 < self.provinceArr.count {
            let firstAddress = self.provinceArr[self.index1]
            detailAddress += firstAddress as! String
        }
        if self.index2 < self.countryArr.count {
            let secondAddress = self.countryArr[self.index2]
            detailAddress += secondAddress as! String
        }
       
        // 此界面显示
        print(detailAddress)
        self.workared.text = detailAddress
        self.workaredPlace.alpha = 0
        
    }
    

    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if indexPath.row == 1{
            self.company.resignFirstResponder()
            self.address.resignFirstResponder()
            self.nickName.resignFirstResponder()
            ActionSheetDatePicker.showPickerWithTitle("出生年月", datePickerMode: UIDatePickerMode.Date, selectedDate: NSDate(), doneBlock: {(picker: ActionSheetDatePicker!, selectedDate: AnyObject!, origin: AnyObject!) -> Void in
                
                let obj = selectedDate as! NSDate
                
                self.beithdayPlace.alpha = 0
                
                self.brithday.text = publicMethod.dataFromString(obj)
                
                }, cancelBlock: {(picker: ActionSheetDatePicker!) -> Void in
                print("cancel")
            }, origin: self.view)



        }
        if indexPath.row == 4{
            self.company.resignFirstResponder()
            self.address.resignFirstResponder()
            
            ActionSheetCustomPicker.showPickerWithTitle("位置区域", delegate: self, showCancelButton: true, origin: self.view, initialSelections: [index1, index2])
        }
        if indexPath.row == 6{
            self.company.resignFirstResponder()
            self.address.resignFirstResponder()
            ActionSheetDatePicker.showPickerWithTitle("入职时间", datePickerMode: UIDatePickerMode.Date, selectedDate: NSDate(), doneBlock: {(picker: ActionSheetDatePicker!, selectedDate: AnyObject!, origin: AnyObject!) -> Void in
                
                let obj = selectedDate as! NSDate
                self.workTimePlace.alpha = 0
               self.workTime.text = publicMethod.dataFromString(obj)
                
                }, cancelBlock: {(picker: ActionSheetDatePicker!) -> Void in
                    print("cancel")
                }, origin: self.view)
        }
    }
    //性别按钮点击事件
    @IBAction func sexBtnClicked(sender: UIButton){
        if sender == self.manBtn{
             sex = "男"
            self.manBtn.setImage(UIImage(named: "checked"), forState: UIControlState.Normal)
            self.femaleBtn.setImage(UIImage(named: "unchecked"), forState: UIControlState.Normal)
        }
        if sender == self.femaleBtn{
            sex = "女"
            
            self.manBtn.setImage(UIImage(named: "unchecked"), forState: UIControlState.Normal)
            
            self.femaleBtn.setImage(UIImage(named: "checked"), forState: UIControlState.Normal)
            
        }
    }
    //提交
    @IBAction func onClick(sender: UIButton) {
        if self.nickName.text == ""{
            SVProgressHUD.showErrorWithStatus("请输入昵称")
            return
        }
        if self.brithday.text == ""{
            SVProgressHUD.showErrorWithStatus("请选择生日")
           
            return
        }
        if self.sex == ""{
            SVProgressHUD.showErrorWithStatus("请选择性别")
            
            return
        }
        if self.company.text == ""{
            SVProgressHUD.showErrorWithStatus("请选择企业名称")
            
            return
        }
        if self.workared.text == ""{
            SVProgressHUD.showErrorWithStatus("请选择工作区域")
           
            return
        }
        if self.address.text == ""{
            SVProgressHUD.showErrorWithStatus("请选择工作地址")
          
            return
        }
        if self.workTime.text == ""{
            SVProgressHUD.showErrorWithStatus("请选择开始时间")
           
            return
        }else{
            self.compleInfo()
        }
    }
    
    //MARK:NETWORKING
    //上传信息
    func compleInfo(){
       
        var param = ["membertypecn":self.memberType!, "birthday":self.brithday.text!, "sex":self.sex!, "unitaddress":self.address.text!, "jointime":self.workTime.text!,"unitname":self.company.text!,"unitarea":self.workared.text!,"name": self.nickName.text!,"phone": self.phone, "pass": self.passWord]
        if self.registType == "qq" {
            
            param = ["membertypecn":self.memberType!, "birthday":self.brithday.text!, "sex":self.sex!, "unitaddress":self.address.text!, "jointime":self.workTime.text!,"unitname":self.company.text!,"unitarea":self.workared.text!,"name": self.nickName.text!,"phone": self.phone, "pass": self.passWord,"qq":self.identyCode!]
        }
        if self.registType == "weixin" {
            
             param = ["membertypecn":self.memberType!, "birthday":self.brithday.text!, "sex":self.sex!, "unitaddress":self.address.text!, "jointime":self.workTime.text!,"unitname":self.company.text!,"unitarea":self.workared.text!,"name": self.nickName.text!,"phone": self.phone, "pass": self.passWord,"weixin":self.identyCode!]
        }
        
        if self.registType == "sina" {
            param = ["membertypecn":self.memberType!, "birthday":self.brithday.text!, "sex":self.sex!, "unitaddress":self.address.text!, "jointime":self.workTime.text!,"unitname":self.company.text!,"unitarea":self.workared.text!,"name": self.nickName.text!,"phone": self.phone, "pass": self.passWord,"sina":self.identyCode!]
        }
        let nilArr: [UIImage] = []
        SVProgressHUD.showWithStatus("加载中...")
        DataTool.uploadLicense(nilArr, uploadStyleImage: nilArr,imgsrc: self.img!, type: "注册", param: param, completionHandler: { (newModel) in
            guard let newDataes = newModel else {
                return
            }
            SVProgressHUD.dismiss()
            print(newDataes)
            self.msg = newDataes
            //分为三种个人,美容院,企业
        
            self.loginAction()
            NSUserDefaults.standardUserDefaults().setObject(self.msg!.type, forKey: "k_UD_type")
            
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "k_UD_isComplete")
            
            NSUserDefaults.standardUserDefaults().synchronize()
           
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
          
            self.navigationController?.popToRootViewControllerAnimated(true)
        })
    }
    
    func loginAction(){
        let token = NSUserDefaults.standardUserDefaults().stringForKey("k_UD_token")
        let phone = NSUserDefaults.standardUserDefaults().objectForKey("k_UD_user")
        let passWord = NSUserDefaults.standardUserDefaults().objectForKey("k_UD_pass")
        
        DataTool.login(phone! as! String, pass: passWord! as! String ,token: token, completionHandler:{ (newModel) in
            guard let newDataes = newModel else {
                return
            }
            print(newDataes)
            
            if newDataes.msg == "登陆成功"{
                
                NSUserDefaults.standardUserDefaults().setBool(true, forKey: "k_UD_isLogin")
                
                NSUserDefaults.standardUserDefaults().synchronize()
                
            }else{
                
                return
            }
            
        })
    }


}
